package com.example.lenovo_.myactivity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Toast;

import com.example.lenovo_.healthyangel.R;
import com.example.lenovo_.myactivity.User.User;
import com.example.lenovo_.myutils.SendUtils;
import com.example.lenovo_.myutils.SharedPfUtils;
import com.example.lenovo_.myutils.UrlUtils;
import com.example.lenovo_.myutils.UserUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by lenovo- on 2017/10/10.
 */
public class RegisterActivity extends Activity implements View.OnClickListener {
    private Button bt1;
    private EditText et1, et2, et3, et4;
    private RadioButton sex1,sex2;
    private RadioGroup rg;
    private static ProgressDialog dialog;
    private String TAG = "info";
    private static String PHPSESSID = null;
    User user = new User();
    hander h1 = new hander();
    SendUtils send = new SendUtils();
//    private SharedPfUtils mSharedManager;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register);
        bt1 = (Button) findViewById(R.id.button4);
        et1 = (EditText) findViewById(R.id.editText6);
        et2 = (EditText) findViewById(R.id.editText3);
        et3 = (EditText) findViewById(R.id.editText4);
        et4 = (EditText) findViewById(R.id.editText5);
        sex1 = (RadioButton) findViewById(R.id.sex_button1);
        sex2 = (RadioButton) findViewById(R.id.sex_button2);
        rg = (RadioGroup) findViewById(R.id.sex_group);
        RadioGrouplistener listener = new RadioGrouplistener();
        rg.setOnCheckedChangeListener(listener);//给rg对象绑定监听器
        bt1.setOnClickListener(this);
        send.setRequestPath(UrlUtils.UrlUserReg);
    }

    class RadioGrouplistener implements OnCheckedChangeListener {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            if(checkedId == R.id.sex_button1){
                user.setSex("1");
            }
            else if(checkedId == R.id.sex_button2){
                user.setSex("0");
            }
        }
    }

    @Override
    public void onClick(View v) {
        if (checkRegister()) {
            StartRequest();//请求服务器端
        }
    }

    public class hander extends Handler {
        @Override
        public void handleMessage(Message msg) {
            int flag = msg.what;
            switch (flag) {
                case 1:
                    show(1);
                    break;
                case 2:
                    show(2);
                    break;
                case 3:
                    show(3);
                    break;
                case 4:
                    show(4);
                    break;
                default:
                    break;
            }
        }
    }

    public void show(int i) {
        if (dialog != null) {
            dialog.dismiss();
        }
        switch (i) {
            case 1:
                if (dialog == null) {
                    dialog = new ProgressDialog(this);
                }
                dialog.setTitle("再等人家一会嘛~");//弹出一个Dialog
                dialog.setMessage("正在注册中...");
                dialog.setCancelable(true);
                dialog.show();
                Timer timer = new Timer();
                timer.schedule(new Task(),2000);
                Toast.makeText(this, "注册成功", Toast.LENGTH_SHORT).show();
                break;
            case 2:
                Toast.makeText(this, "用户已存在", Toast.LENGTH_SHORT).show();
                break;
            case 3:
                Toast.makeText(this, "服务器故障", Toast.LENGTH_SHORT).show();
                break;
            case 4:
                Toast.makeText(this, "连接超时，请检查网络", Toast.LENGTH_SHORT).show();
                break;
            default:
                break;
        }
    }

    //实现延时跳转
    private class Task extends TimerTask {

        @Override
        public void run() {
            startActivity(new Intent(RegisterActivity.this,LoginActivity.class));
        }
    }

    private boolean checkRegister() {
        //若4个editText都不空时
        if (!et1.getText().toString().equals("") && !et2.getText().toString().equals("") && !et3.getText().toString().equals("") && !et4.getText().toString().equals("")&& (sex1.isChecked()||sex2.isChecked())) {
            if(et4.getText().toString().equals(et3.getText().toString())){
                //将信息传递到服务器
                user.setName(et1.getText().toString());
                user.setPhonenumber(et2.getText().toString());
                user.setPassword(et3.getText().toString());
                return true;
            }else {
                Toast.makeText(this,"密码不一致，请重新输入",Toast.LENGTH_SHORT).show();
                return false;
            }
        }else {
            Toast.makeText(this,"请填写完整",Toast.LENGTH_SHORT).show();
            return false;
        }
    }
    private void StartRequest(){
        //新建线程
        new Thread(){
            public void run(){
                try {
                    sendRequest();
                } catch (Exception e){
                    e.printStackTrace();
                }
            }
        }.start();
    }
    private void sendRequest() throws IOException, JSONException {
        HttpURLConnection urlcon=null;
        URL ServerUrl = null;
        int code;
        try{
            //通过HttpURLConnection完成发送请求
            //请求WEB资源
            ServerUrl = new URL(send.getRequestPath());

            //准备传输的数据
            send.setSendRequest(new JSONObject());
            send.getSendRequest().put("username",user.getPhonenumber());
            send.getSendRequest().put("password",user.getPassword());
            send.getSendRequest().put("sex",user.getSex());
            System.out.println(send.getSendRequest().toString());

            urlcon = (HttpURLConnection) ServerUrl.openConnection();
            //使用post的方式
            urlcon.setRequestMethod("POST");
            //连接主机超时，通过setConnectTimeOut方法
            urlcon.setConnectTimeout(30000);
            //从主机读取数据超时，通过setReadTimeout方法
            urlcon.setReadTimeout(30000);
            // 发送POST请求必须设置如下两行
            urlcon.setDoOutput(true);
            urlcon.setDoInput(true);
            // Post 请求不能使用缓存
            urlcon.setUseCaches(false);
            // 设定传送的内容类型是json对象，(如果不设此项,在传送序列化对象时,当WEB服务默认的不是这种类型时可能抛java.io.EOFException)
            urlcon.setRequestProperty("Content-Type", "application/json");
            // 连接，从上述url.openConnection()至此的配置必须要在connect之前完成，
            urlcon.connect();
            // 现在通过输出流对象构建对象输出流对象，以实现输出可序列化的对象。
            DataOutputStream objOutputStrm = new DataOutputStream(urlcon.getOutputStream());
            // 向对象输出流写出数据，这些数据将存到内存缓冲区中
            objOutputStrm.writeBytes(send.getSendRequest().toString());

            // flush输出流的缓冲
            objOutputStrm.flush();
            objOutputStrm.close();

            code = urlcon.getResponseCode();

            if(code==200){
                InputStream intStrm =urlcon.getInputStream();

                // 得到接收到的Json对象，并将原inputstream流转化成json对象
                BufferedReader streamReader = new BufferedReader(new InputStreamReader(intStrm, "UTF-8"));
                StringBuilder responseStrBuilder = new StringBuilder();

                String inputStr;
                try {
                    while ((inputStr = streamReader.readLine()) != null)
                        responseStrBuilder.append(inputStr);
                    System.out.println(responseStrBuilder.toString());
                    //得到Json对象
                    JSONObject jsonObject = new JSONObject(responseStrBuilder.toString());
                    send.setReceResponce(jsonObject);
                    System.out.println(jsonObject.toString());

                    // 获取返回的数据
                    JSONObject jsonObjectdata = send.getReceResponce().getJSONObject("data");
                    System.out.println("注册时返回的用户信息为：" + jsonObjectdata);
                    int flag = jsonObjectdata.getInt("flag");

                    System.out.println(1);
                    Log.i(TAG, "读取到数据 ");
                    System.out.println(2);
                    Log.i(TAG, "flag:" + flag);
                    System.out.println(3);
                    if (flag==1){
//                        String tempUserName = jsonObjectdata.getString("name");
//                        String tempUserPsw = jsonObjectdata.getString("password");
//                        int tempUserId = jsonObjectdata.getInt("id");
//                        String tempUserUrl = jsonObjectdata.getString("head");
//
//                        mSharedManager.setIsKeepUser(true);
//                        mSharedManager.setName(tempUserName);
//                        mSharedManager.setPassword(tempUserPsw);
//                        mSharedManager.setId(tempUserId);
//                        mSharedManager.setUserImgUrl(tempUserUrl);
//
//                        // 初始化全局用户
//                        UserUtils.user.setUserId(tempUserId + "");
//                        UserUtils.user.setUserName(tempUserName);
//                        UserUtils.user.setUserPsw(tempUserPsw);
//                        UserUtils.user.setUserImgUrl(tempUserUrl);
//
//                        System.out.println("用户名为：" + UserUtils.user.getUserName());

                        System.out.println(4);
                        h1.sendEmptyMessage(1);//成功
                    }else if (flag==2){
                        System.out.println(5);
                        h1.sendEmptyMessage(2);//用户名已存在
                    }else {
                        h1.sendEmptyMessage(3);//服务器故障
                    }
                }catch (IOException e){
                    e.printStackTrace();
                    Log.e(TAG, "请求错误 ");// 没有网会抛出异常（连不上）或者一个错的url（为何会超时不管用？秒显示）
                    Log.e(TAG, e.getMessage());
                    h1.sendEmptyMessage(4);//无连接网络
                }
                //封装数据并发送

            }
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            if (urlcon != null) {
                urlcon.disconnect();//关闭连接
            }
        }
    }
}

